<template>
	<view class="create-coupon">
		<view class="create-project-form">
			<view class="create-item">
				<text class="info-item-title">卡券名称</text>
				<input class="info-item-input" type="text" maxlength="21" placeholder-class="placeholderFontClass"
					placeholder="字数上限为21个" v-model="couponName">
			</view>

			<view class="create-item">
				<text class="info-item-title">卡券类型</text>
				<input class="info-item-input" type="text" @click="handleOpenTypePopup"
					placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择卡券类型"
					v-model="couponTypeSelected">
				<uni-icons class="right-arrow-icon" type="forward" size="14" color="#999"></uni-icons>
			</view>

			<view class="create-item" v-if="couponType == 'NORMAL'">
				<text class="info-item-title">优惠金额</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass" placeholder="单位:元"
					v-model="discount_amount">
			</view>

			<view class="create-item" v-if="couponType == 'DISCOUNT'">
				<text class="info-item-title">折扣比例</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="示例值:86,则为八六折" v-model="discount_percent">
			</view>

			<view class="create-item" v-if="couponType == 'EXCHANGE'">
				<text class="info-item-title">单品换购价</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass" placeholder="单位:元"
					v-model="exchange_price">
			</view>

			<view class="create-item">
				<text class="info-item-title">消费门槛</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass" placeholder="单位:元"
					v-model="transaction_minimum">
			</view>

			<view class="create-item-column">
				<text class="info-item-title">活动规则</text>
				<uni-easyinput class="info-item-textarea" type="textarea" v-model="coupon_description"
					placeholder-class="placeholderFontClass" placeholder="用于说明详细的活动规则，会展示在代金券详情页"></uni-easyinput>
			</view>



			<view class="create-item">
				<text class="info-item-title">适用范围</text>
				<input class="info-item-input" type="text" maxlength="15" placeholder-class="placeholderFontClass"
					placeholder="描述商品可用范围" v-model="useRange">
			</view>

			<view class="create-item">
				<text class="info-item-title">生效时间</text>
				<picker mode="date" :value="startValidDate" :start="startDateLimit" :end="endDateLimit"
					@change="bindStartDateChange">
					<view class="date-picker" :class="{'placeholder-text': startValidDate == '有效期最长为1年'}">
						{{startValidDate}}
					</view>
				</picker>
			</view>

			<view class="create-item">
				<text class="info-item-title">失效时间</text>
				<picker mode="date" :value="endValidDate" :start="failureStartDateLimit" :end="failureEndDateLimit"
					@change="bindEndDateChange">
					<view class="date-picker" :class="{'placeholder-text': endValidDate == '有效期最长为1年'}">
						{{endValidDate}}
					</view>
				</picker>
			</view>

			<view class="create-item">
				<text class="info-item-title">有效天数</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="券生效后x天内有效" v-model="after_receive">
			</view>

			<view class="create-item">
				<text class="info-item-title">发放数量</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="请输入发放数量" v-model="sendNum">
			</view>

			<view class="create-item">
				<text class="info-item-title">用户可领数量</text>
				<input class="info-item-input" type="number" placeholder-class="placeholderFontClass"
					placeholder="每个用户最多100张券" v-model="receiveNum">
			</view>

			<view class="create-item-column">
				<text class="info-item-title">卡券备注</text>
				<uni-easyinput class="info-item-textarea" maxlength="20" type="textarea" v-model="remark"
					placeholder-class="placeholderFontClass" placeholder="用于自定义信息,仅自己可见,字数上限为20个"></uni-easyinput>
			</view>

		</view>

		<button class="create-btn" @click.stop.prevent="handleCreate">确认创建</button>

		<!-- 卡券类型popup -->
		<van-popup :show="couponTypePopShow" position="bottom">
			<van-picker show-toolbar :columns="couponTypeList" @confirm="onCouponTypeConfirm"
				@cancel="couponTypePopShow = false" />
		</van-popup>

	</view>
</template>

<script>
	import apiRqs from '@/api/api-request.js';
	import getDateTime from '@/common/getDateTime.js';
	export default {
		data() {
			return {
				couponName: "",
				useRange: "",
				couponType: "",
				couponTypeSelected: "",
				couponTypePopShow: false,
				couponTypeList: ['固定面额满减券', '折扣券', '换购券'],
				startValidDate: "有效期最长为1年",
				endValidDate: "有效期最长为1年",
				sendNum: "",
				after_receive: "",
				receiveNum: "",
				remark: "",
				startDateLimit: "",
				endDateLimit: "",
				failureStartDateLimit: "",
				failureEndDateLimit: "",
				discount_amount: "", // 优惠金额
				discount_percent: "", // 折扣比例
				exchange_price: "", // 单品换购价
				transaction_minimum: "", // 消费门槛
				coupon_description: "", // 卡券说明细则
			}
		},
		onLoad() {},
		methods: {
			// 获取当前日期戳
			getCurDateNum() {
				const cur_date = getDateTime.dateTimeStr('y-m-d h:i:s');
				const date = cur_date.split(" ")[0];
				const time = cur_date.split(" ")[1];
				const year = date.split("-")[0];
				const month = date.split("-")[1];
				const day = date.split("-")[2];
				const hour = time.split(":")[0];
				const min = time.split(":")[1];
				const sec = time.split(":")[2];
				return year + month + day + hour + min + sec;
			},
			// 打开卡券类型
			handleOpenTypePopup() {
				this.couponTypePopShow = true;
			},
			// 确认卡券类型
			onCouponTypeConfirm(val) {
				this.couponTypePopShow = false;
				const value = val.detail.value;
				if (value == '固定面额满减券') {
					this.couponType = 'NORMAL';
				} else if (value == '折扣券') {
					this.couponType = 'DISCOUNT';
				} else if (value == '换购券') {
					this.couponType = 'EXCHANGE';
				}
				this.couponTypeSelected = value;
				console.log('已选卡券类型', this.couponType);
			},
			// 确认创建
			handleCreate() {
				let {
					couponName,
					remark,
					useRange,
					couponType,
					startValidDate,
					endValidDate,
					discount_amount,
					discount_percent,
					exchange_price,
					transaction_minimum,
					sendNum,
					receiveNum,
					after_receive,
					coupon_description,
				} = this;
				const logo_media = uni.getStorageSync("logo_media");
				if (couponName == "") {
					getApp().showToast('卡券名称不能为空');
					return false;
				} else if (couponType == "") {
					getApp().showToast('请选择卡券类型');
					return false;
				} else if (couponType == "NORMAL" && (discount_amount == "" || discount_amount == 0)) {
					// 商户券类型为满减券时，优惠金额需≥1
					getApp().showToast('优惠金额需≥1');
					return false;
				} else if (couponType == "NORMAL" && (transaction_minimum == "" || transaction_minimum == 0)) {
					// 商户券类型为满减券时，消费门槛需≥1
					getApp().showToast('消费门槛需≥1');
					return false;
				} else if (couponType == "DISCOUNT" && discount_percent == "") {
					getApp().showToast('请填写折扣比例');
					return false;
				} else if (couponType == "DISCOUNT" && (transaction_minimum == "" || transaction_minimum == 0)) {
					// 商户券类型为折扣券时，消费门槛需≥1
					getApp().showToast('消费门槛需≥1');
					return false;
				} else if (couponType == "EXCHANGE" && exchange_price == "") {
					getApp().showToast('请填写单品换购价');
					return false;
				} else if (couponType == "EXCHANGE" && transaction_minimum == "") {
					// 商户券类型为换购券时，消费门槛需≥0
					getApp().showToast('请填写消费门槛');
					return false;
				} else if (useRange == "") {
					getApp().showToast('适用范围不能为空');
					return false;
				} else if (startValidDate == '有效期最长为1年') {
					getApp().showToast('请填写生效时间');
					return false;
				} else if (endValidDate == '有效期最长为1年') {
					getApp().showToast('请填写失效时间');
					return false;
				} else if (sendNum == '' || sendNum == 0) {
					getApp().showToast('发放数量需≥1');
					return false;
				} else if (receiveNum == '') {
					getApp().showToast('请填写用户可领数量');
					return false;
				}
				const cur_date = this.getCurDateNum();
				const tokenInfo = uni.getStorageSync("tokenInfo");
				const couponTokenInfo = uni.getStorageSync("couponTokenInfo");
				const rqsData = {
					"stock_name": couponName,
					"belong_merchant": couponTokenInfo.SubMchId,
					"comment": remark,
					"goods_name": useRange,
					"stock_type": couponType,
					"coupon_use_rule": {
						"coupon_available_time": {
							"available_begin_time": `${startValidDate}T00:00:00+08:00`,
							"available_end_time": `${endValidDate}T23:59:59+08:00`,
							"available_day_after_receive": after_receive * 1,
							"available_week": {
								"week_day": [
									0,
									1,
									2,
									3,
									4,
									5,
									6
								],
								"available_day_time": [{
									"begin_time": 1,
									"end_time": 86399
								}]
							},
							"irregulary_avaliable_time": null
						},
						"use_method": "OFF_LINE",
						"mini_programs_appid": "wxadc26d832d9c62d2",
						"mini_programs_path": "/pages/workbench/workbench"
					},
					"stock_send_rule": {
						"max_coupons": sendNum * 1,
						"max_coupons_per_user": receiveNum * 1 > 100 ? 100 : receiveNum * 1,
						"max_coupons_by_day": 100,
						"natural_person_limit": true,
						"prevent_api_abuse": true,
						"transferable": true,
						"shareable": true
					},
					"out_request_no": couponTokenInfo.SubMchId + cur_date + "01",
					"display_pattern_info": {
						"description": coupon_description,
						"merchant_logo_url": "",
						"merchant_name": tokenInfo.shopName,
						"background_color": "Color020"
					},
					"coupon_code_mode": "WECHATPAY_MODE"
				};
				if (logo_media.logo_media_url) {
					rqsData.display_pattern_info.merchant_logo_url = logo_media.logo_media_url;
				} else {
					getApp().showToast("暂未上传商户logo，请先前往上传商户logo");
					return false;
				}
				if (couponType == "NORMAL") {
					let info = {
						"discount_amount": discount_amount * 100,
						"transaction_minimum": transaction_minimum * 100
					};
					rqsData.coupon_use_rule.fixed_normal_coupon = info;
				}
				if (couponType == "DISCOUNT") {
					let info = {
						"discount_percent": discount_percent * 1,
						"transaction_minimum": transaction_minimum * 100
					};
					rqsData.coupon_use_rule.discount_coupon = info;
				}
				if (couponType == "EXCHANGE") {
					let info = {
						"exchange_price": exchange_price * 100,
						"transaction_minimum": transaction_minimum * 100
					};
					rqsData.coupon_use_rule.exchange_coupon = info;
				}
				console.log('请求数据', rqsData);
				console.log('请求数据json', JSON.stringify(rqsData));
				getApp().showLoading();
				apiRqs._createCoupon(rqsData).then((res) => {
					uni.hideLoading();
					console.log('创建卡券结果', res);
					if (res.code == 200 && res.data.resultCode.stateCode == 200) {
						getApp().showToast('创建成功', 'success');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500)
					}
				})
			},
			// 有效开始时间
			bindStartDateChange(e) {
				const value = e.detail.value;
				// 选中开始时间后，结束时间最长为1年
				const endDate = getDateTime.handleGetAssignDay(value, 365);
				console.log('+1年时间', endDate);
				this.failureEndDateLimit = endDate;
				if (this.endValidDate != "有效期最长为1年") {
					this.endValidDate = "有效期最长为1年";
				}
				this.startValidDate = value;
				this.failureStartDateLimit = value;
			},
			// 有效结束时间
			bindEndDateChange(e) {
				const value = e.detail.value;
				// 选中开始时间后，结束时间-开始时间最长为1年
				const startDate = getDateTime.handleGetAssignDay(value, -365);
				console.log('-1年时间', startDate);
				if (this.startValidDate == "有效期最长为1年") {
					this.startDateLimit = startDate;
				}
				this.endValidDate = value;
				this.endDateLimit = value;
			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.create-coupon {
		.create-project-form {
			margin: 20px;

			.create-item {
				display: flex;
				align-items: center;
				width: 100%;
				border-bottom: 1px solid #f5f5f5;
				background-color: #fff;
				padding: 16px 15px;
				box-sizing: border-box;
				position: relative;

				.right-arrow-icon {
					position: absolute;
					right: 10px;
				}

				&:first-child {
					border-top: 1px solid #f5f5f5;
					border-top-left-radius: 4px;
					border-top-right-radius: 4px;
				}

				&:last-child {
					border-bottom-left-radius: 4px;
					border-bottom-right-radius: 4px;
				}

				.info-item-title {
					width: 100px;
					flex: 0 0 100px;
					font-size: 14px;
					margin-right: 10px;
				}

				.date-picker {
					font-size: 14px;
					color: #666;

					&.placeholder-text {
						color: #ddd;
					}
				}

				.info-item-input {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
				}

				.placeholderFontClass {
					color: #ddd;
				}
			}

			.create-item-column {
				display: flex;
				flex-direction: column;
				width: 100%;
				border-bottom: 1px solid #f5f5f5;
				background-color: #fff;
				padding: 16px 15px;
				box-sizing: border-box;
				position: relative;

				.right-arrow-icon {
					position: absolute;
					right: 10px;
				}

				.info-item-title {
					width: 100px;
					font-size: 14px;
					margin-right: 10px;
				}

				.date-picker {
					font-size: 14px;
					color: #666;

					&.placeholder-text {
						color: #ddd;
					}
				}

				.info-item-input,
				.uni-easyinput {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
					margin-top: 10px;

					.is-input-border {
						border-color: #f5f5f5 !important;
					}
				}



				.placeholderFontClass {
					color: #ddd;
				}
			}
		}

		.create-btn {
			margin: 20px;
			border: none;
			background-color: #FFA53D;
			color: #fff;
			font-size: 15px;
			height: 35pt;
			line-height: 35pt;
			box-shadow: inset 0px 4px 7px 0px rgba(255, 255, 255, 0.33);

			&::after {
				border: none;
			}

			&:active {
				background-color: rgba(255, 141, 10, 1);
			}
		}
	}
</style>